<?php

namespace app\admin\model;

use think\Model;

/**
 * People
 */
class People extends Model
{
    // 表名
    protected $name = 'people';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'city_text',
    ];

    protected static function onAfterInsert($model): void
    {
        if (is_null($model->weigh)) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getDescriptionAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function getPhotosAttr($value): array
    {
        return handle_full_urls($value);
    }

    public function setPhotosAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getVideoThumbnailsAttr($value): array
    {
        return handle_full_urls($value);
    }

    public function setVideoThumbnailsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getVideoUrlsAttr($value): array
    {
        return handle_full_urls($value);
    }

    public function setVideoUrlsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getCityAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setCityAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getAvatarAttr($value): string
    {
        return handle_full_urls($value, true);
    }
    public function getCityTextAttr($value, $row): string
    {
        if ($row['city'] === '' || $row['city'] === null) return '';
        $cityNames = \think\facade\Db::name('area')->whereIn('id', $row['city'])->column('name');
        return $cityNames ? implode(',', $cityNames) : '';
    }

    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
    }
}
